import dayjs from "dayjs";
import { NumericTypes } from "mongoose";
import { BaseMongoClient } from "../controller/mongodb";
import { ClientInterface, DailyReportInterface, FaucetInterface, FiveMinitesReportInterface, HourlyReportInterface, LastPaidInterface, ReportInterface } from '../model'
import uuid from 'uuid'

//初始化hour
export async function initDataHour(clients: ClientInterface) {
    const { now_hour } = getTime()
    let hourArr: HourlyReportInterface[] = new Array()
    const time = new Date().getTime()
    console.log("hour_report添加开始")

    const five_datas = await clients.fiveClient.getMany({})
    const hour_datas = await clients.hourClient.getMany({})
    const faucet_datas = await clients.faucetClient.getMany({})
    const five_map = createTotalMap(five_datas)
    const hour_map = createTotalMap(hour_datas)
    for (const item of faucet_datas) {
        let hour_total = hour_map.get(item._id) || 0
        let five_total = five_map.get(item._id)
        let total: number = Number(five_total) - Number(hour_total)
        hourArr.push(
            {
                _id: uuid.v1(),
                faucet_id: item._id,
                // total:Math.random()*5,
                total: total,
                timezone:String(now_hour)
                // timezone: dayjs(new Date("2021-07-23 17:00:00")).unix()+''
            }
        )
    }
    console.log(`hour_report表添加时间${new Date().getTime() - time}`)
    return hourArr
}

//初始化daily_report
export async function initDataDaily(clients: ClientInterface) {
    const dailyArr: DailyReportInterface[] = new Array()
    const { now_day } = getTime()

    const time = new Date().getTime()
    console.log("daily_report添加开始")
    const daily_datas = await clients.dailyClient.getMany({})
    const five_datas = await clients.fiveClient.getMany({})
    const faucet_data = await clients.faucetClient.getMany({})

    const five_map = createTotalMap(five_datas)
    const daily_map = createTotalMap(daily_datas)
    for (const item of faucet_data) {
        let daily_total = daily_map.get(item._id) || 0
        let five_total = five_map.get(item._id)
        let total: number = Number(five_total) - Number(daily_total)
        dailyArr.push(
            {
                _id: uuid.v1(),
                faucet_id: item._id,
                // total:Math.random()*5,
                total: total,
                timezone: String(now_day)
                // timezone:dayjs(new Date("2021-07-23 00:00:00")).unix()+''
            }
        )
    }
    console.log(`daily_report表添加时间${new Date().getTime() - time}`)
    return dailyArr
}

//初始化five_report
export function initDataFive(data: any, faucet_id: string, insertTime: number) {
    const fiveArr: FiveMinitesReportInterface = {
        _id: uuid.v1(),
        faucet_id: faucet_id,
        total: data.paid_today,
        timezone: String(insertTime)
    }
    return fiveArr
}

//初始化faucet
export function initDataFaucet(faucet_data: any): FaucetInterface {

    const faucet: FaucetInterface = {
        _id: uuid.v1(),
        id: faucet_data.id,
        balance: faucet_data.balance,
        name: faucet_data.name,
        currency: faucet_data.currency,
        url: faucet_data.url,
        timezone: faucet_data.creation_date,
        owner_id: faucet_data.owner_id,
        owner_name: faucet_data.owner_name,
        total_users_paid: faucet_data.owner_name,
        health: faucet_data.health,
        active_users: faucet_data.active_users,
        category: faucet_data.category,
    }
    return faucet

}

//初始化last_paid
export function initDataLastPaid(lastPaidData: any, insertTime: number, last_paid_data_id: string): LastPaidInterface {

    const last_paid: LastPaidInterface = {
        _id: uuid.v1(),
        last_paid_mins: 0,
        faucet_id: last_paid_data_id,
        paid_today: lastPaidData.paid_today,
        operationTime: String(insertTime)
    }
    return last_paid;
}

export function getTime(t?: any) {
    const now = t ? dayjs(t) : dayjs()
    let min = now.startOf('minute').add(1, 'minute')
    let last_month = now.startOf('day').subtract(30,'day')
    let last_day = now.startOf('hour').subtract(1,'day')
    return {
        now_min: min.unix(),
        now_hour: now.startOf('hour').unix(),
        now_day: now.startOf('day').unix(),
        now_week: now.startOf('day').subtract(7, 'day').unix(),
        last_month:last_month.unix(),
        last_day:last_day.unix()
    }
}

export function createMapData<T>(data: T[]): Map<string, T> {
    let map = new Map<string, T>();
    for (const item of data) {
        let element: any = item
        map.set(element.faucet_id, item)
    }
    return map
}

/**
 * 科学计数法转为普通数字
 * @param inputNumber
 * @returns 
 */
export function transferToNumber(inputNumber: any): Promise<number> {
    if (isNaN(inputNumber)) {
        return inputNumber
    }
    inputNumber = '' + inputNumber
    inputNumber = parseFloat(inputNumber)
    const eformat = inputNumber.toExponential() // 转换为标准的科学计数法形式（字符串）
    let pos = eformat.indexOf('e')
    const baseValue = eformat.substr(0, pos)
    const power = eformat.substr(pos + 1)
    let bitNumber = 0
    pos = baseValue.indexOf('.')
    if (pos === -1) {
        bitNumber = 0 - power
    } else {
        let float = baseValue.substr(pos + 1)
        bitNumber = float.length - power
    }
    const number = inputNumber.toFixed(Math.max(0, bitNumber))
    return number
}



export function createTotalMap<T>(datas: T[]) {

    const map = new Map<string, number>();

    for (const element of datas) {
        let item: any = element
        let total = map.get(item.faucet_id) || 0
        total += Number(item.total)
        map.set(item.faucet_id, total)
    }

    return map

}


